import { createRouter, createWebHashHistory } from 'vue-router'
// 引入视图组件
// import ArticleView from '@/views/ArticleView.vue'
// import LoginView from '@/views/LoginView.vue'
// import RegisterView from '@/views/RegisterView.vue'
// import LayoutView from '@/views/LayoutView.vue'
// import HomeView from '@/views/tabbar/HomeView.vue'
// import CollectView from '@/views/tabbar/CollectView.vue'
// import LikeView from '@/views/tabbar/LikeView.vue'
// import UserView from '@/views/tabbar/UserView.vue'
import { getStorageToken } from '@/utils/storage'
// 组件懒加载，导入写法变成了函数，当路由匹配时，再调用函数加载组件
const ArticleView = () => import('@/views/ArticleView.vue')
const LoginView = () => import('@/views/LoginView.vue')
const RegisterView = () => import('@/views/RegisterView.vue')
const LayoutView = () => import('@/views/LayoutView.vue')
const HomeView = () => import('@/views/tabbar/HomeView.vue')
const CollectView = () => import('@/views/tabbar/CollectView.vue')
const LikeView = () => import('@/views/tabbar/LikeView.vue')
const UserView = () => import('@/views/tabbar/UserView.vue')

const router = createRouter({
  history: createWebHashHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/article/:id',
      component: ArticleView, // 文章详情页
      meta: {
        title: '文章详情',
      },
    },
    {
      path: '/login',
      component: LoginView, // 登录页
      meta: {
        title: '登录',
      },
    },
    {
      path: '/register',
      component: RegisterView, // 注册页
      meta: {
        title: '注册',
      },
    },
    {
      path: '/',
      component: LayoutView, // 首页布局容器
      redirect: '/home', // 重定向到首页
      children: [
        {
          path: 'home',
          component: HomeView, // 首页
          meta: {
            title: '首页',
          },
        },
        {
          path: 'collect',
          component: CollectView, // 收藏
          meta: {
            title: '收藏',
          },
        },
        {
          path: 'like',
          component: LikeView, // 喜欢
          meta: {
            title: '喜欢',
          },
        },
        {
          path: 'user',
          component: UserView, // 我的
          meta: {
            title: '我的',
          },
        },
      ],
    },
  ],
})

// 路由白名单
const whiteList = ['/login', '/register']

// 路由守卫 - beforeEach 前置导航守卫
router.beforeEach((to) => {
  // 如有路由中有标题信息
  if (to.meta.title) {
    // 设置页面标题为：标题名称 | 网站名称
    document.title = to.meta.title + ' | 面经'
  }
  // 路由鉴权
  const token = getStorageToken()
  // 是否有 token
  if (token) {
    // 有 token 直接放行
    return true // 放行 to.path
  } else {
    // 判断是否为白名单
    if (whiteList.includes(to.path)) {
      return true // 放行到 to.path
    } else {
      return '/login' // 重定向到登录页
    }
  }
})

export default router
